from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.template import Context, loader
from django.shortcuts import render_to_response
from google.appengine.api import users
from django.utils  import simplejson as json
import logging
from google.appengine.api import memcache
from django.core import serializers
import time
from home.models import Note
from datetime import datetime


def post_nost(request): 
  user = users.get_current_user()
  if user:   
  	nickname = user.nickname()
  	gmail = user.email()
  	noteContent = request.REQUEST.get('note', '')
	now = datetime.now()
  	note = Note(notePoster=nickname,gmail=gmail,noteContent=noteContent,postDate=now)
  	note.put() 	
  	notes = memcache.get("notes")
  	
        if notes is not None:
	  jNote = dict();
	  jNote['notePoster'] =nickname;
	  jNote['gmail'] =gmail;
	  jNote['noteContent'] =noteContent;
	  jNote['postDate']=str(now)
	  #put the latest note first
  	  notes=json.dumps(jNote)+','+notes
	  try:
	    if  memcache.delete("notes") == memcache.DELETE_SUCCESSFUL :
	      logging.info("update ok")
	      if not memcache.add("notes", notes):
                logging.error("Memcache set failed.")
	      else :
		notes = memcache.get("notes")
		logging.info("new notes in chahe:"+notes)
	    else :
	      logging.info("update failed")
	  except Exception,e:
            logging.error("e:%s",e)
  	
  else:
        logging.warn("Invalid update request from "+request.get_host())
    
        
def request_update(request):
  notes = memcache.get("notes")
  if notes is None:
        logging.info("######notes in cache expired")
        notes =''
        results = Note.all().order('-postDate')
	notesCount = results.count()   
	notesContent = serializers.serialize("json",results)  
	rows = json.loads(notesContent)
	for i in range(0,notesCount):	  
	  row = rows[i]['fields']
	  row = json.dumps(row)
	  notes = str(notes)  + row + ',' 
        if not memcache.add("notes", notes,120):
          logging.error("Memcache set failed.")
	logging.info("Complite db query:"+notes);
  else :
        logging.info("get notes from cache")
  s = '['+ notes +']'
   
  return HttpResponse(s);

  
def request_delete(request):  
  user = users.get_current_user()
  if user:   
  	nickname = user.nickname()
  	gmail = user.email()
  	noteContent = request.REQUEST.get('noteContent', '');
  	query = Note.gql("WHERE gmail = :1 AND noteContent = :2",gmail,noteContent)
  	query.fetch(1)[0].delete()
   	logging.info("note deleted");
  else:
        logging.warn("Invalid request_delete request from "+request.get_host())


def profile(request):
  d = dict();
  user = users.get_current_user()  
  gmail = ""
  nickname = ""
  if user:
    gmail= user.email()
    nickname = user.nickname()
    sign_url = users.create_logout_url("/")
  else:
    sign_url = users.create_login_url("/")  
  d['gmail']=gmail
  d['nickname']=nickname
  d['sign_url']=sign_url
  data =  json.dumps(d)
  return HttpResponse('['+data+']');


def index(request):
  return HttpResponseRedirect('www/h/Home.html')



	
